package com.example.sunmiv1.activity;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.sunmiv1.R;
import com.example.sunmiv1.adapter.AddCreditUserAdapter;
import com.example.sunmiv1.base.BaseActivity;
import com.example.sunmiv1.base.bean;
import com.example.sunmiv1.dialog.SetCreditMoneyDialog;
import com.example.sunmiv1.entity.CreditVipListInfo;
import com.example.sunmiv1.utils.Tools;
import com.example.sunmiv1.utils.net.ACache;
import com.example.sunmiv1.utils.net.Common;
import com.example.sunmiv1.utils.net.GsonUtils;
import com.example.sunmiv1.utils.net.HttpUtils;
import com.example.sunmiv1.utils.net.LoadingDialog;
import com.example.sunmiv1.utils.net.TextCallBack;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class AddCreditUserActivity extends BaseActivity {


    @BindView(R.id.title_back)
    ImageView titleBack;
    @BindView(R.id.title_title)
    TextView titleTitle;
    @BindView(R.id.addCreditUser_listView)
    PullToRefreshListView addCreditUserListView;
    @BindView(R.id.addCreditUser_custom)
    TextView addCreditUserCustom;
    @BindView(R.id.addCreditUser_confirm)
    TextView addCreditUserConfirm;
    @BindView(R.id.addCreditUser_edit)
    EditText addCreditUserEdit;
    @BindView(R.id.addCreditUser_search)
    ImageView addCreditUserSearch;

    private LoadingDialog loadingDialog;
    private int page = 1;
    private Context context;
    private CreditVipListInfo creditVipListInfo;
    private String storeQuota = "";
    private AddCreditUserAdapter addCreditUserAdapter;
    private List<CreditVipListInfo.DataBean.ListBean> list = new ArrayList<>();
    private int size = 0;
    private ACache aCache;
    private int allSize = 0;

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    for (CreditVipListInfo.DataBean.ListBean bean : creditVipListInfo.getData().getList()) {
                        bean.setQuota(storeQuota);
                        list.add(bean);
                    }
                    allSize = creditVipListInfo.getData().getTotal();
                    setSize();
                    setAddCreditUserAdapter();
                    break;
            }
        }
    };

    @Override
    protected void initView() {
        setContentView(R.layout.activity_add_credit_user);
        ButterKnife.bind(this);
        context = this;
        aCache = ACache.get(context);
        loadingDialog = new LoadingDialog(this);
        titleTitle.setText(R.string.addCreditUser);
    }

    @Override
    protected void initData() {
        setSize();
        getStoreQuota();
    }

    private void setSize() {
        addCreditUserConfirm.setText("添加"+"(" + size + "/" + allSize + ")");
    }

    @Override
    protected void initListener() {
        addCreditUserListView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                size = 0;
                setSize();
                page = 1;
                list.clear();
                setAddCreditUserAdapter();
                getVipList();
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                page++;
                getVipList();
            }
        });
    }

    @OnClick({R.id.title_back, R.id.addCreditUser_custom, R.id.addCreditUser_confirm,R.id.addCreditUser_search})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.title_back:
                finish();
                break;
            case R.id.addCreditUser_custom:
                JSONArray jsonArray = new JSONArray();
                for (CreditVipListInfo.DataBean.ListBean bean : list) {
                    if (bean.isCheck()) {
                        JSONObject json = new JSONObject();
                        try {
                            json.put("credit_id", bean.getId());
                            json.put("quota", bean.getQuota());
                            jsonArray.put(json);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }
                }
                if (jsonArray.length() == 0) {
                    Toast.makeText(context, "請先選擇批量設置額度的用戶", Toast.LENGTH_SHORT).show();
                    return;
                }
                SetCreditMoneyDialog.newInstance(jsonArray, 2)
                        .callback(o -> {
                            for (CreditVipListInfo.DataBean.ListBean bean : list) {
                                if (bean.isCheck()) {
                                    bean.setQuota(o.toString());
                                }
                            }
                            setAddCreditUserAdapter();
                        })
                        .startShow(getSupportFragmentManager(), "")
                        .setCancelable(false);
                break;
            case R.id.addCreditUser_confirm:
                addCreditVip();
                break;
            case R.id.addCreditUser_search:
                size = 0;
                setSize();
                page = 1;
                list.clear();
                setAddCreditUserAdapter();
                getVipList();
                break;
        }
    }

    private void setAddCreditUserAdapter() {
        if (addCreditUserAdapter == null) {
            addCreditUserAdapter = new AddCreditUserAdapter(list);
            addCreditUserListView.setAdapter(addCreditUserAdapter);
        } else {
            addCreditUserAdapter.notifyDataSetChanged();
        }
        addCreditUserAdapter.setCallBack((type, position) -> {
            if (size >= allSize && type == 1) {
                list.get(position).setCheck(false);
                setAddCreditUserAdapter();
                return;
            }
            if (type == 1) {
                size++;
            } else {
                size--;
            }
            addCreditUserConfirm.setText("添加"+"(" + size + "/" + allSize + ")");
        });
    }

    /**
     * 獲取門店默認賒賬額度
     */
    private void getStoreQuota() {
        JSONObject jsonObject = new JSONObject();
        jsonObject = Tools.createParameterCode(jsonObject);
        HttpUtils.post(context, Common.GET_STORE_QUOTA, jsonObject, new TextCallBack() {
            @Override
            protected void onSuccess(String text) {
                try {
                    JSONObject json = new JSONObject(text);
                    if (json.getInt("status") == 1) {
                        storeQuota = json.getString("quota");
                        getVipList();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            protected void onFailure(ResponseException e) {

            }
        });
    }

    /**
     * 獲取會員列表
     */
    private void getVipList() {
        loadingDialog.show();
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("page", page);
            jsonObject.put("limit", "20");
            jsonObject.put("search", addCreditUserEdit.getText().toString().trim());
            jsonObject = Tools.createParameterCode(jsonObject);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        HttpUtils.post(context, Common.GET_CREDIT_VIP_LIST, jsonObject, new TextCallBack() {
            @Override
            protected void onSuccess(String text) {
                loadingDialog.dismiss();
                addCreditUserListView.onRefreshComplete();
                try {
                    JSONObject json = new JSONObject(text);
                    if (json.getInt("status") == 1) {
                        creditVipListInfo = GsonUtils.JsonToBean(text, CreditVipListInfo.class);
                        Message msg = new Message();
                        msg.what = 1;
                        handler.sendMessage(msg);
                    } else {
                        Toast.makeText(context, json.getString("msg"), Toast.LENGTH_SHORT).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            protected void onFailure(ResponseException e) {
                loadingDialog.dismiss();
                addCreditUserListView.onRefreshComplete();
            }
        });
    }


    /**
     * 添加賒賬用戶
     */
    private void addCreditVip() {
        JSONArray jsonArray = new JSONArray();
        for (CreditVipListInfo.DataBean.ListBean bean : list) {
            if (bean.isCheck()) {
                if (TextUtils.isEmpty(bean.getQuota()) || Double.parseDouble(bean.getQuota()) <= 0) {
                    Toast.makeText(context, "賒賬額度不能小於等於0", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (Double.parseDouble(bean.getQuota()) > Double.parseDouble(storeQuota)) {
                    Toast.makeText(context, "賒賬額度不能大於門店額度", Toast.LENGTH_SHORT).show();
                    return;
                }
                JSONObject json = new JSONObject();
                try {
                    json.put("id", bean.getId());
                    json.put("quota", bean.getQuota());
                    jsonArray.put(json);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }
        if (jsonArray.length() == 0) {
            Toast.makeText(context, "請先選擇用戶", Toast.LENGTH_SHORT).show();
            return;
        }
        loadingDialog.show();
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("arr", jsonArray);
            if ("3".equals(aCache.getAsString("userType"))) {
                jsonObject.put("editor_type", "1");
            } else {
                jsonObject.put("editor_type", "2");
            }
            jsonObject = Tools.createParameterCode(jsonObject);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        HttpUtils.post(context, Common.ADD_CREDIT_USER, jsonObject, new TextCallBack() {
            @Override
            protected void onSuccess(String text) {
                loadingDialog.dismiss();
                try {
                    JSONObject json = new JSONObject(text);
                    Toast.makeText(context, json.getString("msg"), Toast.LENGTH_SHORT).show();
                    if (json.getInt("status") == 1) {
                        if (json.has("defeatArr")) {
                            String msg = "";
                            JSONArray info = json.getJSONArray("defeatArr");
                            for (int i = 0; i < info.length(); i++) {
                                msg = msg + info.getString(i) + "\n";
                            }
                            Toast.makeText(context, msg, 5).show();
                        }
                        finish();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            protected void onFailure(ResponseException e) {
                loadingDialog.dismiss();
            }
        });
    }
}
